package stage_1_module_4.code.homework_5;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

public class ClientReceiveThread extends Thread {
    private Socket s;

    @Override
    public void run() {

        try {
            while (true) {
                ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
                Message m = (Message) ois.readObject();
                if (m.getType() == 1) {
                    System.out.println(m.getName() + "发来的消息:"+m.getMsg());
                } else {
                    System.out.println(m.getName()+"发来文件:"+m.getMsg());
                    DataInputStream dis = new DataInputStream(s.getInputStream());
                    int len = dis.readInt();
                    String fname = "./stage_1_module_4/code/homework_5/receive/"+Thread.currentThread().getName()+m.getMsg();
                    FileOutputStream fos = new FileOutputStream(fname);
                    byte[] b = new byte[len];
                    dis.read(b, 0, len);
                    fos.write(b);
                    fos.flush();
                    fos.close();
                }
            }

        } catch (IOException | ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public ClientReceiveThread (Socket s) {
        this.s = s;
    }
}
